package org.vison.wonfu.framework.soa.exception;

import org.vison.wonfu.framework.soa.BaseRuntimeException;
import org.vison.wonfu.framework.soa.Invocation;

import java.net.URL;

public class RpcException extends BaseRuntimeException {
    private static final long serialVersionUID = -5446537390081935067L;

    public static final int UNKNOWN_EXCEPTION = 0;
    public static final int NETWORK_EXCEPTION = 1;
    public static final int TIMEOUT_EXCEPTION = 2;
    public static final int BIZ_EXCEPTION = 3;
    public static final int FORBIDDEN_EXCEPTION = 4;
    public static final int SERIALIZATION_EXCEPTION = 5;
    public static final int NO_INVOKER_AVAILABLE = 6;
    public static final int UNIMPLEMENTED = 9;
    public static final int NO_INSTANCE_AVAILABLE = 7;
    /**
     * SOA定义错误
     */
    public static final int SOA_DEFINITION = 10;

    public static final int GOVERNANCE = 100;
    public static final int FALLBACK = 101;

    private int code;

    public RpcException(int code) {
        super();
        this.code = code;
    }

    public RpcException(int code, String message, Throwable cause) {
        super(message, cause);
        this.code = code;
    }

    public RpcException(int code, String message) {
        super(message);
        this.code = code;
    }

    public RpcException(int code, Throwable cause) {
        super(cause);
        this.code = code;
    }

    public static RpcException getRpcException(int code, URL url, Invocation invocation, Throwable e) {
        if (e instanceof RpcException) {
            return (RpcException) e;
        }

        return new RpcException(code, "Failed to invoke remote method: " + invocation.getMethodName()
                + ", provider: " + url + ", cause: " + e.getMessage(), e);
    }


    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public boolean isBiz() {
        return code == BIZ_EXCEPTION;
    }

    public boolean isForbidden() {
        return code == FORBIDDEN_EXCEPTION;
    }

    public boolean isTimeout() {
        return code == TIMEOUT_EXCEPTION;
    }

    public boolean isNetwork() {
        return code == NETWORK_EXCEPTION;
    }

    public boolean isSerialization() {
        return code == SERIALIZATION_EXCEPTION;
    }

    public boolean isNoInvokerAvailable() {
        return code == NO_INVOKER_AVAILABLE;
    }

    public boolean isUnimplemented() {
        return code == UNIMPLEMENTED;
    }

    public boolean isGovernance() {
        return code == GOVERNANCE;
    }

    public boolean isFallback() {
        return code == FALLBACK;
    }

}
